//
//  XXD.swift
//  XXSwiftDemo
//
//  Created by admin on 2022/3/28.
//

import Foundation
//import HandyJSON

public extension Dictionary {
    
    typealias XXDictionaryEchoBlock = (String,Any)->Bool
    
    var data:Data?{
        var data: Data?
        try? data = JSONSerialization.data(withJSONObject: self, options: .prettyPrinted)
        return data
    }
    
    var json:String {
        if let d = self.data{
            guard let jsonStr = String.init(data: d, encoding: .utf8) else{
                return ""
            }
            return jsonStr
        }else{
            return ""
        }
    }
    
    var array:Array<Any>{
        
        var values:Array<Any> = []
        for key in self.keys {
            values.append(self[key] as Any)
        }
        return values
    }
    
//    func model<T: HandyJSON>(_ model: T.Type) -> T {
//        let dic:NSDictionary = self as NSDictionary
//        let model:T = JSONDeserializer<T>.deserializeFrom(dict: dic) ?? T.init()
//        return model
//    }

    func value (_ key: String) -> Any {
        if !(self[key as! Key] is NSNull) {
            
            if self[key as! Key] != nil {
                return self[key as! Key] as Any
            }
        }
        return ""
    }
    
    func string(_ key:String) -> String {
        if !(self[key as! Key] is NSNull) {
            if self[key as! Key] != nil {
                return self[key as! Key] as! String
            }
        }
        return ""
    }
    
    func merge(_ dic:NSDictionary) -> NSDictionary {
        var newDic:Dictionary = self
        for (key,value) in dic{
            newDic[key as! Key] = (value as! Value)
        }
        return newDic as NSDictionary
    }
    
    func echo(_ block:XXDictionaryEchoBlock){
        for (key,value) in self{
            if !block(key as! String,value){
                break
            }
        }
    }
}
